/**
 * Created by KaiBo on 2016/7/4.
 */
//项目ROOT
var workpath='/./';
$(document).ready(function () {
    //添加规格项目
    var selectArr = new Array("颜色", "尺寸", "尺码", "规格", "款式", "净含量", "种类", "内存", "版本", "容量");
    $(".add-group").click(function () {
        var index = $(this).parents("form").children(".spec").length;//获取规格数
        index++;
        $("#normsnum").val(index);

        var myDate = new Date();
        var s = myDate.getTime().toString();
        s = "S" + index;

        var html = '<div class="form-group spec">';
        html += '   <div class="col-sm-4">';
        html += '       <select name=' + s + ' class="form-control">';
        for (var i = 0; i < selectArr.length; i++) {
            html += '<option value=' + selectArr[i] + '>' + selectArr[i] + '</option>';
        }
        html += '       </select>';
        html += '   </div>';
        html += '   <div class="col-sm-2  text-left">';
        html += '       <div class="checkbox">';
        html += '           <label>';
        html += '               <input class="checkbox-item" type="checkbox"> 添加规格图片';
        html += '           </label>';
        html += '       </div>';
        html += '   </div>';
        html += '   <div class="col-sm-4  text-left">';
        html += '       <div class="input-group">';
        html += '           <input type="text" class="form-control" placeholder="添加规格项">';
        html += '           <span class="input-group-btn">';
        html += '               <button class="btn add-spec-option btn-default" type="button">添加</button>';
        html += '           </span>';
        html += '       </div>';
        html += '   </div>';
        html += '   <div class="col-sm-2 text-right">';
        html += '      <h5><span class="glyphicon close-spec glyphicon-remove-circle"></span></h5>';
        html += '   </div>';
        html += '   <div class="col-sm-12 text-left spec-list">';
        html += '        <div><button type="button" class="btn add-spec-item btn-default" >+添加</button></div>';
        html += '   </div>';
        html += '</div>';


        $(this).parents(".form-group").before(html);
        if (index >= 3) {
            $("#add-group").slideUp("slow");
            index = 3;
        }
    });

    //添加下拉菜单选项
    $(document).on("click", ".add-spec-option", function () {
        var $elem = $(this);
        var val = $elem.parent().prev("input").val();
        var $select = $elem.parents(".spec").find("select");

        $elem.parent().prev("input").val("");
        if (selectArr.indexOf(val) < 0) {
            selectArr.push(val);
            alert("添加成功");
        } else {
            alert("已存在此规格项");
            return;
        }
        $select.html("");
        for (var i = 0; i < selectArr.length; i++) {
            var html = '<option value=' + selectArr[i] + '>' + selectArr[i] + '</option>';
            $select.append(html);
        }
        //$select.val(val);
    });


    //弹出提示框
    var content = '<div class="row">';
    content += '  <div class="col-xs-8"><input type="text"  class="form-control" placeholder="添加规格值"></div>';
    content += '<div class="col-xs-4"><button type="button" class="btn btn-ok btn-primary">确定</button></div>';
    content += '</div>';


    //动态添加弹窗插件
    $(document).on("mouseover", ".add-spec-item", function () {
        var $elem = $(this);
        $elem.popover({
            html: true,
            content: content
        });
    });

    //关闭提示框
    $(document).on("click", ".btn-cancel", function () {
//            var $elem = $(this).parents(".popover").prev(".add-spec-item");
//            $elem.popover('hide')
    });

    //判断元素是否在数组中
    function contains(arry, elem) {
        var i = arry.length;
        while (i--) {
            if (arry[i][1] == elem) {
                return true;
            }
        }
        return false;
    }


    //添加规格值
    var specArray0 = new Array();
    var specArray1 = new Array();
    var specArray2 = new Array();
    var checkbox = false;  //判断checkbox是否选中
    $(document).on("click", ".btn-ok", function () {
        var $elem = $(this);
        var $add = $elem.parents(".popover").prev(".add-spec-item");//添加按钮
        var index = $elem.parents("form").children(".spec").index($add.parents(".spec"));//获取触发事件的位置
        var specVal = $elem.parent("div").prev().children("input").val();//获取值

        specVal = specVal.trim();//去除空格
        if (specVal == "") {
            return;
        }
        //判断是否存在相同规格值
        switch (index) {
            case 0:
                if (contains(specArray0, specVal)) {
                    alert("已存在此规格值");
                    return;
                }
                break;
            case 1:
                if (contains(specArray1, specVal)) {
                    alert("已存在此规格值");
                    return;
                }
                break;
            case 2:
                if (contains(specArray2, specVal)) {
                    alert("已存在此规格值");
                    return;
                }
                break;
            default:
                alert("未知错误！");
        }

        var Dindex = 0; //计算规格值数量
        Dindex = $add.parent("div").siblings(".spec-item").length;

        var detail = $(this).parents(".spec").find("select").attr("name");
        detail = detail.substr(1, detail.length - 1);
        var Idetail = "I" + detail; //图片路径
        detail = "D" + detail;

        var html = "";
        if (checkbox) {
            html = '<div class="spec-item active">';
            html += '    <div class="spec-img">';
            html += '        <div class="add-img">';
            html += '            <img title="点击更换" class="img-responsive" src="" alt="">';
            html += '        </div>';
            html += '    </div>';
        } else {
            html = '<div class="spec-item">';
        }
        html += '       <input type="text" id=' + Idetail + Dindex + ' hidden name=' + Idetail + ' >';
        html += '       <input type="text" hidden name=' + detail + ' value=' + specVal + '>';
        html += '       <input type="button" data-img=' + Idetail + Dindex + ' name=' + detail + ' class="btn btn-block btn-default" value=' + specVal + '>';
        html += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
        html += '</div>';


        var html2 = '<div class="spec-item">';
        html2 += '       <input type="text" hidden name=' + detail + ' value=' + specVal + '>';
        html2 += '       <input type="button" name=' + detail + ' class="btn btn-block btn-default" value=' + specVal + '>';
        html2 += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
        html2 += '  </div>';

        $add.popover('destroy');//隐藏并销毁元素的弹出框

        var temp = new Array();
        temp.push(detail);
        temp.push(specVal);
        switch (index) {
            case 0:
                $add.parent("div").before(html);//显示规格值
                specArray0.push(temp);
                break;
            case 1:
                $add.parent("div").before(html2);//显示规格值
                specArray1.push(temp);
                break;
            case 2:
                $add.parent("div").before(html2);//显示规格值
                specArray2.push(temp);
                break;
            default:
                alert("未知错误！");
        }

        showTable($("form"), 8, $(".table"));
    });


    //删除规格值
    $(document).on("click", ".close-spec-item", function () {
        var $elem = $(this);
        var index = $elem.parents("form").children(".spec").index($elem.parents(".spec"));//获取触发事件的位置
        var specVal = $elem.parents("div").children("input").val();//获取值

        var Dindex = $elem.parents(".spec-list").children(".spec-item").index($elem.parents(".spec-item"));


        switch (index) {
            case 0:
                //$add.parent("div").before(html);//显示规格值
                specArray0.splice(Dindex, 1);
                break;
            case 1:
                //$add.parent("div").before(html2);//显示规格值
                specArray1.splice(Dindex, 1);
                break;

            case 2:
                //$add.parent("div").before(html2);//显示规格值
                specArray2.splice(Dindex, 1);
                break;
            default:
                alert("未知错误！");
        }

        $elem.parents(".spec-item").remove();
        showTable($("form"), 8, $(".table"));
    });

    //构建表格
    function showTable($form, first, $table) {
        var spec1len = specArray0.length > 0 ? specArray0.length : 1;//数组1长度
        var spec2len = specArray1.length > 0 ? specArray1.length : 1;//数组2长度
        var spec3len = specArray2.length > 0 ? specArray2.length : 1;//数组3长度
        var sum = spec1len * spec2len * spec3len;

        var second = first + 1;
        var third = first + 2;
        var spec1 = '<td>' + $form.children(".spec:nth-child(" + first + ")").find("select").val() + '</td>';
        var spec2 = '<td>' + $form.children(".spec:nth-child(" + second + ")").find("select").val() + '</td>';
        var spec3 = '<td>' + $form.children(".spec:nth-child(" + third + ")").find("select").val() + '</td>';


        spec1 = specArray0.length > 0 ? spec1 : " ";
        spec2 = specArray1.length > 0 ? spec2 : " ";
        spec3 = specArray2.length > 0 ? spec3 : " ";


        var html = '<tr>' + spec1 + spec2 + spec3 + '<td >价格（元）</td><td>库存</td><td>商家编码</td></tr>';

        $table.html(html);
        for (var i = 0; i < spec1len; i++) {
            var name = "";
            var spec1Name = "";
            if (specArray0.length > 0) {
                spec1 = specArray0[i][1];
                name += specArray0[i][0] + i + "-";
                spec1Name = name;
            }
            for (var j = 0; j < spec2len; j++) {
                var spec2Name = "";
                name = spec1Name;
                if (specArray1.length > 0) {
                    spec2 = specArray1[j][1];
                    name += specArray1[j][0] + j + "-";
                }
                spec2Name = name;
                for (var k = 0; k < spec3len; k++) {
                    name = spec2Name;
                    html = '<tr>';
                    if (specArray0.length > 0) {
                        html += '<td >' + spec1 + '</td>';
                    }
                    if (specArray1.length > 0) {
//                            if (j % (sum / specArray1.length) == 0) {
                        html += '<td >' + spec2 + '</td>';
//                            }
                    }
                    if (specArray2.length > 0) {
                        html += '<td >' + specArray2[k][1] + '</td>';
                        name += specArray2[k][0] + k + "-";
                    }

                    name = name.replace(/\[/g, "");
                    name = name.replace(/\]/g, "");
                    name = name.substr(0, name.length - 1);
                    name = name.trim();

                    if (name != "") {
                        html += '<td width="100px"><input type="text" name=' + name + ' class="form-control" placeholder=""></td>';
                        html += '<td width="80px"><input type="text" name=' + name + ' class="goods-stock form-control" placeholder=""></td>';
                        html += '<td width="80px"><input type="text" name=' + name + ' class="form-control" placeholder=""></td>';
                    }

                    html += '</tr>';
                    $table.append(html);
                }
            }
        }
    }
    //库存取消焦点事件计算库存
    $(document).on("blur",".goods-stock",function(){
        var stockSum = 0;
        $(".table tr").each(function(){
            var $elem = $(this);
            var stock = $elem.find(".goods-stock").val();
            if(stock == null || stock == "" ||stock == undefined){
                stock = 0;
            }
            stockSum += parseInt(stock);
        });
        $("#stocksum").val(stockSum);
    });
    //减少规格项目
    $(document).on("click", ".close-spec", function () {
        var $elem = $(this);
        var index = $elem.parents("form").children(".spec").length;//获取规格数

        var $spec = $elem.parents(".spec");
        var Sindex = $elem.parents("form").children(".spec").index($spec);//获取规格位置
        var $add = $(this).parents(".spec").find(".add-spec-item");
        $add.popover('destroy');//隐藏并销毁元素的弹出框

        switch (Sindex) {
            case 0:
                specArray0 = specArray1;
                specArray1 = specArray2;
                specArray2 = [];
                break;
            case 1:
                specArray1 = specArray2;
                specArray2 = [];
                break;
            case 2:
                specArray2 = [];
                break;
            default:
                alert("未知错误！");
        }

        $("#add-group").slideDown("slow");
        $(this).parents(".form-group").remove();
        checkbox = false;  //判断checkbox是否选中

        showTable($("form"), 8, $(".table"));
    });

    //重新选择下拉菜单
    $(document).on("change", " .spec select", function () {
        var $elem = $(this);
        var $spec = $elem.parents(".spec");
        var Sindex = $elem.parents("form").children(".spec").index($spec);//获取规格位置

        switch (Sindex) {
            case 0:
                specArray0 = [];
                break;
            case 1:
                specArray1 = [];
                break;
            case 2:
                specArray2 = [];
                break;
            default:
                alert("未知错误！");
        }

        var $speclist = $spec.find(".spec-list");
        $speclist.children(".spec-item").remove();

        showTable($("form"), 8, $(".table"));
    });

    //添加规格图片
    $(document).on("change", ".spec .checkbox-item", function () {
        var $specItem = $(this).parents(".spec").children(".spec-list").find(".spec-item");
        var $add = $(this).parents(".spec").find(".add-spec-item");
        $add.popover('destroy');//隐藏并销毁元素的弹出框

        var html = '<div class="spec-img">';
        html += '   <div class="add-img">';
        html += '        <img title="点击更换" class="img-responsive" src="" alt="">';
        html += '    </div>';
        html += '   </div>';
        if ($(this).attr("checked")) {
            $specItem.removeClass("active");
            $specItem.each(function () {
                $(this).children(".spec-img").remove();
            });

            $(this).attr("checked", false);
            checkbox = false;
        } else {
            $specItem.addClass("active");
            $specItem.each(function () {
                $(this).prepend(html);
            });
            $(this).attr("checked", true);
            checkbox = true;
        }
    });



    //删除商品图片
    $(document).on("click", ".close-goods-img", function () {
        var $elem = $(this);
        var $imgList = $elem.parents(".goods-img-list");
        var index =$imgList.children(".goods-img-item").index($elem.parent(".goods-img-item"));
        var sum = $imgList.children(".goods-img-item").length;
        index = index + sum + 2;
        if(confirm("确认移除？")){
            $goodsid=$("#goodsid").val();
            $goodspicid= $imgList.children("input:nth-child("+index+")").val();
            $imgList.children("input:nth-child("+index+")").remove();
            $elem.parent(".goods-img-item").remove();
        }
    });

    //添加商品
    $(".btn-next").click(function () {
        var type = $("input[name='typenew']").val();
        if(type == '' || type.length <= 0){
            $("input[name='typenew']").focus();
            return ;
        }
        var json = $('#Frm').FrmJSON();
        $.ajax({
            type: "POST",
            url: workpath+"Admin/Goods/saveGoods",
            data: {
                dataform: json,
            },
            dataType: "json",
            success: function (result) {
                alert(result.info);
                window.location.href=workpath+"Admin/Goods/editGoodsinfoShow?goodsid="+result.goodsid;
            },
            error: function () {
                alert('添加失败');
            }
        });
    });
});

function UpdateFolders(){
    /*获取文件夹列*/
    $.post(workpath+"Admin/Picasa/Folders",{},function (data){
        var folder = eval(data);
        var html = '';
        for (var i = 0; i < folder.length; i++) {
            html += '<a href="#" data-id="';
            if(folder[i]['unid'] == ''){
                html += folder[i]['unid'];
                html += '" class="list-group-item active">';
            }else{
                html += folder[i]['unid'];
                html += '" class="list-group-item">';
            }
            html += folder[i]['filename'];
            var number = folder[i]['sum']==null?0:folder[i]['sum'];
            html += '<span class="badge">' + number;
            html += '</span></a>';
        };
        $("#Folders-content").html(html);
        click_search();
    });
    /*获取文件夹列*/
}
